<?php
declare (strict_types = 1);

namespace app\common\model;

use think\Model;
use think\model\concern\SoftDelete;
class AdminDepartment extends Model
{
    use SoftDelete;
     protected $deleteTime = false;
    // 获取列表
    public static function getList()
    {
        $where = [];
        $list = self::makeTree(self::field('dept_id as id,parent_id,name as title')->where($where)->select()->toArray());
        return ['status' => [
            'code' => 200,
            'message' => '操作成功'
        ], 'data' => $list, 'msg' => 'success'];
    }

    public static function makeTree($data)
    {
        $res = [];
        $tree = [];

        // 整理数组
        foreach ($data as $key => $vo) {
            $res[$vo['id']] = $vo;
        }
        unset($data);

        // 查询子孙
        foreach ($res as $key => $vo) {
            if($vo['parent_id'] != 0) {
                $res[$vo['parent_id']]['children'][] = &$res[$key];
            }
        }

        // 去除杂质
        foreach ($res as $key => $vo) {
            if(isset($vo['parent_id']) && $vo['parent_id'] == 0) {
                $tree[] = $vo;
            }
        }
        unset($res);

        return $tree;
    }
}
